package com.yskj.tms.wxutil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import com.yskj.tms.wxconfig.WxPayConfig;
import org.apache.commons.lang.StringUtils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;



public class WeiMaCreate {
	
	public static void main(String[] args) {

		String orderno = "2017041712404002";
		String payurl = WeiMaCreate.getCodeurl(orderno, "0.01", "微信支付");
		WeiMaCreate.createWeima(payurl, orderno, "D:\\");
	}

	/**
	 * 
	 * @param payurl  支付二维码地址
	 * @param orderno 订单号
	 * @param path 图片存放路径
	 * @return
	 */
	public static String  createWeima(String payurl,String orderno,String path){
		String msg = null;
		try{
			if (StringUtils.isNotBlank(payurl)) {
				int width = 300;
				int height = 300;
				String format = "png";
				Hashtable hints = new Hashtable();
				hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
				BitMatrix bitMatrix;
				try {
					bitMatrix = new MultiFormatWriter().encode(payurl,BarcodeFormat.QR_CODE, width, height, hints);
					File outputFile = new File(path + orderno + ".png");
					MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
				} catch (WriterException e) {
					msg = "二维码生成错误";
				}
			}else{
				msg = "生成微信支付链接失败";
			}
		}catch(Exception e){
			msg = "生成支付二维码失败";
		}
		return msg;
	}
	
	
	/**
	 * 获取微信扫码支付二维码连接
	 * @param orderno 订单号
	 * @param money  订单金额(单位元)
	 * @param bodyinfo 描述
	 * @return
	 */
	public static String getCodeurl(String orderno,String money,String bodyinfo){
		// 1 参数
		// 订单号
		String orderId = orderno;
		// 附加数据 原样返回
		String attach = "";
		// 总金额以分为单位，不带小数点
		String totalFee = getMoney(money);
		
		// 订单生成的机器 IP
		String spbill_create_ip = "127.0.0.1";
		// 这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
		String notify_url = WxPayConfig.callback;
		String trade_type = "NATIVE";

		// 商户号
		String mch_id = WxPayConfig.partner;
		// 随机字符串
		String nonce_str = getNonceStr();

		// 商品描述根据情况修改
		String body = bodyinfo;
		// 商户订单号
		String out_trade_no = orderId;

		SortedMap<String, String> packageParams = new TreeMap<String, String>();
		packageParams.put("appid", WxPayConfig.appid);
		packageParams.put("mch_id", mch_id);
		packageParams.put("nonce_str", nonce_str);
		packageParams.put("body", body);
		packageParams.put("attach", attach);
		packageParams.put("out_trade_no", out_trade_no);

		// 这里写的金额为1 分到时修改
		packageParams.put("total_fee", totalFee);
		packageParams.put("spbill_create_ip", spbill_create_ip);
		packageParams.put("notify_url", notify_url);
		packageParams.put("trade_type", trade_type);

		RequestHandler reqHandler = new RequestHandler(null, null);
		reqHandler.init(WxPayConfig.appid, WxPayConfig.appsecret, WxPayConfig.partnerkey);

		String sign = reqHandler.createSign(packageParams);
		String xml = "<xml>" + "<appid>" + WxPayConfig.appid + "</appid>" 
		+ "<mch_id>"+ mch_id + "</mch_id>" 
		+ "<nonce_str>" + nonce_str+ "</nonce_str>" + "<sign>" + sign + "</sign>"
				+ "<body><![CDATA[" + body + "]]></body>" 
				+ "<out_trade_no>" + out_trade_no
				+ "</out_trade_no>" + "<attach>" + attach + "</attach>"
				+ "<total_fee>" + totalFee + "</total_fee>"
				+ "<spbill_create_ip>" + spbill_create_ip
				+ "</spbill_create_ip>" + "<notify_url>" + notify_url
				+ "</notify_url>" + "<trade_type>" + trade_type
				+ "</trade_type>" + "</xml>";
		System.out.println("xml==\n"+xml);
		String code_url = "";
		String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		
		
		code_url = new GetWxOrderno().getCodeUrl(createOrderURL, xml);
		System.out.println("code_url----------------"+code_url);
 
		
		return code_url;
	}
	
	
	/**
	 * 获取随机字符串
	 * @return
	 */
	public static String getNonceStr() {
		Date now = new Date();
		SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		// 随机数
		String currTime = outFormat.format(now);;
		// 8位日期
		String strTime = currTime.substring(8, currTime.length());
		// 四位随机数
		String strRandom = buildRandom(4) + "";
		// 10位序列号,可以自行调整。
		return strTime + strRandom;
	}

	/**
	 * 元转换成分
	 * @param amount
	 * @return
	 */
	public static String getMoney(String amount) {
		if(amount==null){
			return "";
		}
		// 金额转化为分为单位
		String currency =  amount.replaceAll("\\$|\\￥|\\,", "");  //处理包含, ￥ 或者$的金额  
        int index = currency.indexOf(".");  
        int length = currency.length();  
        Long amLong = 0l;  
        if(index == -1){  
            amLong = Long.valueOf(currency+"00");  
        }else if(length - index >= 3){  
            amLong = Long.valueOf((currency.substring(0, index+3)).replace(".", ""));  
        }else if(length - index == 2){  
            amLong = Long.valueOf((currency.substring(0, index+2)).replace(".", "")+0);  
        }else{  
            amLong = Long.valueOf((currency.substring(0, index+1)).replace(".", "")+"00");  
        }  
        return amLong.toString(); 
	}
	
	
	/**
	 * 取出一个指定长度大小的随机正整数.
	 * 
	 * @param length
	 *            int 设定所取出随机数的长度。length小于11
	 * @return int 返回生成的随机数。
	 */
	public static int buildRandom(int length) {
		int num = 1;
		double random = Math.random();
		if (random < 0.1) {
			random = random + 0.1;
		}
		for (int i = 0; i < length; i++) {
			num = num * 10;
		}
		return (int) ((random * num));
	}
}
